<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Loginlib {

    var $CI;
    protected $_table;

    function Loginlib() {

    }

    function login($email = '', $password = '') {
        $this->CI = & get_instance();
        if ($email == '' OR $password == '') {
            return false;
        }
        if ($this->CI->session->userdata('email') == $email) {
            //User is already logged in.
            return false;
        }
        $this->CI->config->load('database_tables');
        $this->_table = $this->CI->config->item('dbtables');
        //Check against user table
        $this->CI->db->where('usu_email', $email);
        $this->CI->db->where('usu_password', md5($password));
        $query = $this->CI->db->get_where($this->_table['usuario']);
        if ($query->num_rows() > 0) {
            $row = $query->row_array();
            $this->CI->session->sess_destroy();
            $this->CI->session->sess_create();
            $this->CI->session->set_userdata( array('idusuario' => $row['usu_idusuario'],
                                                    'nombre' => $row['usu_nombre'],
                                                    'idioma' => $row['usu_idioma'],
                                                    'rol' => $row['usu_rol'],
                                                    'email' => $row['usu_email'],
                                                    'empresa' => $row['usu_empresa'],
                                                    'tab_sel' => 'tarifas'
                                                ));
            $this->CI->db->where('usu_idusuario', $this->CI->session->userdata('idusuario'));
            $this->CI->db->where('usu_empresa', $this->CI->session->userdata('empresa'));
            $this->CI->db->update($this->_table['usuario'], array('usu_ultimoacceso' => date("Y-m-d H:i:s")));
            return true;
        } else {
            return false;
        }
    }

    /**
     * Logout user
     *
     * @access	public
     * @return	void
     */
    function logout() {
        //Put here for PHP 4 users
        $this->CI = & get_instance();
        $this->CI->session->sess_destroy();
    }

}

?>